package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"login-master/cache"
	"login-master/models"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var goods []models.Good
	redis_key := "list_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&goods)

		ass, _ := json.Marshal(goods)

		cache.Rdb.Set(cache.Ctx, redis_key, ass, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &goods)
	}
	var total int64
	models.DB.Model(models.Good{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "列表展示成功",
		"uid":   goods,
		"total": total,
	})
	return
}
func List1(c *gin.Context) {
	id := c.Query("id")
	var user models.Good
	redis_key := "list_id_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id = ?", id).Find(&user)

		sdd, _ := json.Marshal(user)

		cache.Rdb.Set(cache.Ctx, redis_key, sdd, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &user)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "详细查询",
		"data": user,
	})

}
func Like(c *gin.Context) {
	id := c.PostForm("id")
	good_id, _ := strconv.Atoi(c.PostForm("good_id"))
	var user models.Like
	err := models.DB.Where("id = ?", id).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "点赞失败",
		})
		return
	}
	if user.ID > 1 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "点赞重复",
		})
		return
	}
	data := models.Like{
		GoodId: good_id,
	}
	err = models.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "点赞失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "点赞成功",
		})
		return
	}

}
